package cn.starlightsoftware.sherly.framework.mybatisplus.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.starlightsoftware.sherly.framework.security.utils.SecurityUtil;
import cn.starlightsoftware.sherly.model.BaseDO;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author 谷子毅
 */
@Component
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO BaseDO = (BaseDO) metaObject.getOriginalObject();
            DateTime now = DateUtil.date();
            if (ObjUtil.isNull(BaseDO.getCreateTime())) {
                BaseDO.setCreateTime(now);
            }
            if (ObjUtil.isNotNull(SecurityUtil.getLoginUserId()) && ObjUtil.isNull(BaseDO.getCreateUserId())) {
                BaseDO.setCreateUserId(SecurityUtil.getLoginUserId());
            }
            if (ObjUtil.isNull(BaseDO.getUpdateTime())) {
                BaseDO.setUpdateTime(now);
            }
            if (ObjUtil.isNotNull(SecurityUtil.getLoginUserId()) && ObjUtil.isNull(BaseDO.getUpdateUserId())) {
                BaseDO.setUpdateUserId(SecurityUtil.getLoginUserId());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO BaseDO = (BaseDO) metaObject.getOriginalObject();
            BaseDO.setUpdateTime(DateUtil.date());
            BaseDO.setUpdateUserId(SecurityUtil.getLoginUserId());
        }
    }
}
